package utilizadores;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;

import java.awt.Color;

import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public class FormulariosConsulta {

	private final static String SUPER_USER = "admin@eatdrink.pt";

	private JFrame frame;
	private JTextField inputTextName;
	private JTextField inputTextCity;
	private JTextField inputTextSchool;

	GestaoUtilizadores gestUtil = null;;

	FormulariosDetalhe formDet;

	private Connection conn;
	private final String DB_URL = "jdbc:sqlanywhere:Tds:localhost:2638?eng=eatdrink";
	private final String user = "dba";
	private final String password = "sql";

	private Statement s;
	private ResultSet r = null;

	private final int nameJLabelX = 10;
	private int nameJlabelY = 139;
	private final int nameJlabelW = 235;
	private final int nameJlabelH = 24;

	private final int cityJLabelX = 244;
	private int cityJLabelY = 139;
	private final int cityJLabelW = 131;
	private final int cityJLabelH = 24;

	private final int schoolJLabelX = 374;
	private int schoolJLabelY = 139;
	private final int schoolJLabelW = 122;
	private final int schoolJLabelH = 24;

	private int JButtonFollowX = 493;
	private int JButtonFollowY = 139;
	private final int JButtonFollowW = 41;
	private final int JButtonFollowH = 24;

	private String storeNameDBContent[] = new String[10];
	private String storeSchoolDBContent[] = new String[10];

	public String recordID = "";
	private LinkedList<JLabel> mostraLabels = new LinkedList<>();
	private LinkedList<JButton> mostraBotaoFollow = new LinkedList<>();

	public boolean selectFollow = false;

	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FormulariosConsulta window = new FormulariosConsulta();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	public FormulariosConsulta() throws SQLException {
		initialize();
		startDataBase();

		gestUtil = new GestaoUtilizadores(new Utilizador(SUPER_USER));
		List<Utilizador> mostraTodos = gestUtil.getTodosUtilizadores(null);
		loadDBToGUI(mostraTodos);
		// showInfo();
	}

	public void startDataBase() {

		try {
			conn = DriverManager.getConnection(DB_URL, user, password);
		} catch (SQLException e) {

			e.printStackTrace();
		}

		try {

			s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
					ResultSet.CONCUR_READ_ONLY);

		} catch (SQLException e) {

			System.err.println("SQL Error: " + e.getMessage());
		}
	}

	private void loadDBToGUI(List<Utilizador> mostraUtil) throws SQLException {

		String idUtil;
		int a = 0;
		for (Utilizador c : mostraUtil) {
			idUtil = c.getIdUtilizador();
			r = s.executeQuery("Select * FROM Utilizador where email ='"
					+ idUtil + "'");
			while (a < 10 && r.next()) {
				storeNameDBContent[a] = r.getString("nome") + " ->" + idUtil;
				storeSchoolDBContent[a] = r.getString("escola");

				a++;
			}
		}
		conn.close();

	}

	public void showInfo() {

		frame.repaint();
		clearFollowButton();
		clearLabels();

		for (int a = 0; a < storeNameDBContent.length; a++) {
			addJLabelName(a);
			addJLabelSchool(a);
			addJLabelCity(a);
			addButtonFollow(storeNameDBContent[a]);
		}
	}

	private void addButtonFollow(String utilizador) {

		JButton follow = null;
		String storeID = "";

		boolean find = false;
		for (int a = 0; a < utilizador.length(); a++) {
			if (utilizador.charAt(a) == '>') {
				find = true;
			}
			if (find && utilizador.charAt(a) != '>') {
				storeID = storeID + utilizador.charAt(a);
			}
		}
		final String aux = storeID;
		if (seguidor(storeID)) {
			follow = new JButton("-");
		} else {
			follow = new JButton("+");
		}
		follow.setBackground(new Color(30, 144, 255));
		follow.setFont(new Font("Tahoma", Font.PLAIN, 10));
		follow.setBounds(JButtonFollowX, JButtonFollowY, JButtonFollowW,
				JButtonFollowH);
		frame.getContentPane().add(follow);
		JButtonFollowY = JButtonFollowY + JButtonFollowH + 2;

		mostraBotaoFollow.add(follow);

		follow.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				if (arg0.getComponent().toString().contains("+")) {

					gestUtil.follow(aux);

				}
				if (arg0.getComponent().toString().contains("-")) {
					gestUtil.unfollow(aux);
				}
			}
		});

	}

	private boolean seguidor(String storeID) {
		String id = gestUtil.getIdUtilizador();

		boolean found = false;

		try {
			conn = DriverManager.getConnection(DB_URL, user, password);
		} catch (SQLException error) {

			error.printStackTrace();
		}

		try {

			s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
					ResultSet.CONCUR_READ_ONLY);

			r = s.executeQuery("select nome, emailsguidor from Utilizador, follow WHERE emailsgu = '"
					+ id + "' and email = emailsguidor");

			while (r.next()) {
				if (r.getString("emailsguidor").contains(storeID)) {
					found = true;

				}
			}

			conn.close();

		} catch (SQLException error) {

			System.err.println("SQL Error: " + error.getMessage());
		}

		return found;

	}

	private void addJLabelName(int a) {
		final JLabel label = new JLabel("");
		label.setBounds(nameJLabelX, nameJlabelY, nameJlabelW, nameJlabelH);

		label.setText(storeNameDBContent[a]);
		frame.getContentPane().add(label);
		nameJlabelY = nameJlabelY + nameJlabelH + 2;

		label.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent arg0) {

				recordID = "";
				label.setForeground(Color.BLUE);
				String getID = label.getText();

				boolean find = false;
				for (int a = 0; a < getID.length(); a++) {
					if (getID.charAt(a) == '>') {
						find = true;
					}
					if (find && getID.charAt(a) != '>') {
						recordID = recordID + getID.charAt(a);

					}
				}

			}
		});

		mostraLabels.add(label);
	}

	private void addJLabelSchool(int a) {
		JLabel label = new JLabel(" ");
		label.setBounds(schoolJLabelX, schoolJLabelY, schoolJLabelW,
				schoolJLabelH);
		label.setText(storeSchoolDBContent[a]);
		frame.getContentPane().add(label);
		schoolJLabelY = schoolJLabelY + schoolJLabelH + 2;
		mostraLabels.add(label);
	}

	private void addJLabelCity(int a) {
		JLabel label = new JLabel("");
		label.setBounds(cityJLabelX, cityJLabelY, cityJLabelW, cityJLabelH);
		frame.getContentPane().add(label);
		cityJLabelY = cityJLabelY + cityJLabelH + 2;
		mostraLabels.add(label);
	}

	public void clearLabels() {
		for (JLabel l : mostraLabels) {
			l.setText("");
			frame.remove(l);
			frame.repaint();
		}
	}

	public void clearFollowButton() {
		for (JButton b : mostraBotaoFollow) {
			frame.remove(b);
			frame.repaint();
		}
	}

	private void initialize() {

		frame = new JFrame("Pesquisa de utilizador");
		frame.getContentPane().setBackground(new Color(220, 220, 220));
		frame.setBounds(100, 100, 560, 460);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.getContentPane().setLayout(null);

		JLabel labelName = new JLabel("NOME:");
		labelName.setBounds(10, 10, 38, 24);
		frame.getContentPane().add(labelName);

		inputTextName = new JTextField();
		inputTextName.setBounds(49, 10, 485, 24);
		frame.getContentPane().add(inputTextName);
		inputTextName.setColumns(10);

		JLabel labelCity = new JLabel("CIDADE:");
		labelCity.setBounds(10, 46, 50, 24);
		frame.getContentPane().add(labelCity);

		inputTextCity = new JTextField();
		inputTextCity.setColumns(10);
		inputTextCity.setBounds(58, 46, 144, 24);
		frame.getContentPane().add(inputTextCity);

		JLabel labelSchool = new JLabel("ESCOLA:");
		labelSchool.setBounds(227, 46, 50, 24);
		frame.getContentPane().add(labelSchool);

		inputTextSchool = new JTextField();
		inputTextSchool.setColumns(10);
		inputTextSchool.setBounds(278, 46, 256, 24);
		frame.getContentPane().add(inputTextSchool);

		JLabel labelFollow = new JLabel("A SEGUIR?");
		labelFollow.setBounds(10, 81, 61, 24);
		frame.getContentPane().add(labelFollow);

		final JCheckBox checkBoxFollow = new JCheckBox("");
		checkBoxFollow.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				if (checkBoxFollow.isSelected()) {
					selectFollow = true;
				}
			}
		});
		checkBoxFollow.setBackground(new Color(220, 220, 220));
		checkBoxFollow.setBounds(70, 81, 24, 24);
		frame.getContentPane().add(checkBoxFollow);

		JButton buttonSearch = new JButton("Pesquisar!");
		buttonSearch.setBackground(new Color(30, 144, 255));

		buttonSearch.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				String readName = inputTextName.getText();
				String readSchool = inputTextSchool.getText();

				for (int a = 0; a != storeNameDBContent.length; a++) {
					storeNameDBContent[a] = "";
					storeSchoolDBContent[a] = "";
				}
				LinkedList<Utilizador> aux = gestUtil.filtrarUtilizadores(
						readName, readSchool, null);

				int a = 0;
				for (Utilizador u : aux) {

					if (a < 10) {

						try {
							conn = DriverManager.getConnection(DB_URL, user,
									password);
						} catch (SQLException error) {

							error.printStackTrace();
						}

						try {

							s = conn.createStatement(
									ResultSet.TYPE_FORWARD_ONLY,
									ResultSet.CONCUR_READ_ONLY);

							r = s.executeQuery("SELECT nome, escola FROM Utilizador where email='"
									+ u.getIdUtilizador() + "'");

							while (r.next()) {

								storeNameDBContent[a] = r.getString("nome")
										+ " ->" + u.getIdUtilizador();
								storeSchoolDBContent[a] = r.getString("escola");

							}

							nameJlabelY = 139;
							cityJLabelY = 139;
							schoolJLabelY = 139;
							JButtonFollowY = 139;

							conn.close();
							showInfo();
						} catch (SQLException error) {
							error.printStackTrace();
						}

						a++;
					}

				}
				if (selectFollow == true) {

					String id = gestUtil.getIdUtilizador();

					for (int c = 0; c != storeNameDBContent.length; c++) {
						storeNameDBContent[c] = "";
						storeSchoolDBContent[c] = "";
					}

					try {
						conn = DriverManager.getConnection(DB_URL, user,
								password);
					} catch (SQLException error) {

						error.printStackTrace();
					}

					try {

						s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
								ResultSet.CONCUR_READ_ONLY);

						r = s.executeQuery("select nome, emailsguidor from Utilizador, follow WHERE emailsgu = '"
								+ id + "' and email = emailsguidor");

						int b = 0;

						while (b < 10 && r.next()) {
							storeNameDBContent[b] = r.getString("nome") + "->"
									+ r.getString("emailsguidor");

							b++;
						}
						nameJlabelY = 139;
						cityJLabelY = 139;
						schoolJLabelY = 139;
						JButtonFollowY = 139;

						conn.close();
						showInfo();
					} catch (SQLException error) {

						System.err.println("SQL Error: " + error.getMessage());
					}
					selectFollow = false;

				}

			}
		});
		buttonSearch.setBounds(195, 81, 180, 24);
		frame.getContentPane().add(buttonSearch);

		JButton buttonName = new JButton("NOME:");
		buttonName.setBackground(new Color(30, 144, 255));
		buttonName.setBounds(10, 114, 235, 24);
		frame.getContentPane().add(buttonName);
		buttonName.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				clearLabels();
				try {
					conn = DriverManager.getConnection(DB_URL, user, password);
				} catch (SQLException error) {

					error.printStackTrace();
				}

				try {

					s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
							ResultSet.CONCUR_READ_ONLY);

					r = s.executeQuery("SELECT * from Utilizador ORDER BY nome ASC");

					int a = 0;
					while (a < 10 && r.next()) {

						storeNameDBContent[a] = r.getString("nome") + "->"
								+ r.getString("email");
						storeSchoolDBContent[a] = r.getString("escola");

						a++;

					}
					nameJlabelY = 139;
					cityJLabelY = 139;
					schoolJLabelY = 139;
					JButtonFollowY = 139;

					conn.close();
					showInfo();
				} catch (SQLException error) {

					System.err.println("SQL Error: " + error.getMessage());
				}
			}
		});

		JButton buttonCity = new JButton("CIDADE:");
		buttonCity.setBackground(new Color(30, 144, 255));
		buttonCity.setBounds(244, 114, 131, 24);
		frame.getContentPane().add(buttonCity);
		buttonCity.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

			}
		});

		JButton buttonSchool = new JButton("ESCOLA:");
		buttonSchool.setBackground(new Color(30, 144, 255));
		buttonSchool.setBounds(374, 114, 160, 24);
		frame.getContentPane().add(buttonSchool);
		buttonSchool.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				clearLabels();
				try {
					conn = DriverManager.getConnection(DB_URL, user, password);
				} catch (SQLException error) {

					error.printStackTrace();
				}

				try {

					s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
							ResultSet.CONCUR_READ_ONLY);

					r = s.executeQuery("SELECT * from Utilizador ORDER BY escola ASC");

					int a = 0;
					while (a < 10 && r.next()) {

						storeNameDBContent[a] = r.getString("nome") + "->"
								+ r.getString("email");
						storeSchoolDBContent[a] = r.getString("escola");
						a++;

					}
					nameJlabelY = 139;
					cityJLabelY = 139;
					schoolJLabelY = 139;
					JButtonFollowY = 139;

					conn.close();
					showInfo();
				} catch (SQLException error) {

					System.err.println("SQL Error: " + error.getMessage());
				}

			}
		});

		JButton buttonClose = new JButton("SAIR");
		buttonClose.setBackground(new Color(30, 144, 255));
		buttonClose.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				frame.dispose();
				if (gestUtil != null)
					gestUtil.Sair();
			}
		});
		buttonClose.setBounds(10, 398, 160, 24);
		frame.getContentPane().add(buttonClose);

		JButton buttonDetails = new JButton("DETALHES");
		buttonDetails.setBackground(new Color(30, 144, 255));
		buttonDetails.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				String nome = "";
				String email = "";
				String escola = "";

				try {
					conn = DriverManager.getConnection(DB_URL, user, password);
				} catch (SQLException error) {

					error.printStackTrace();
				}

				try {

					s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
							ResultSet.CONCUR_READ_ONLY);

					r = s.executeQuery("SELECT * from Utilizador WHERE email='"
							+ recordID + "'");

					while (r.next()) {

						nome = r.getString("nome");
						email = r.getString("email");
						escola = r.getString("escola");

					}
					conn.close();
				} catch (SQLException error) {

					System.err.println("SQL Error: " + error.getMessage());
				}

				for (int c = 0; c != storeNameDBContent.length; c++) {
					storeNameDBContent[c] = "";
				}

				try {
					conn = DriverManager.getConnection(DB_URL, user, password);
				} catch (SQLException error) {

					error.printStackTrace();
				}

				try {

					s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
							ResultSet.CONCUR_READ_ONLY);

					r = s.executeQuery("select nome, emailsgu from Utilizador, follow WHERE emailsguidor = '"
							+ email + "' and email = emailsgu");

					int b = 0;

					while (b < 3 && r.next()) {
						storeNameDBContent[b] = r.getString("nome") + "->"
								+ r.getString("emailsgu");

						b++;
					}

					conn.close();
					showInfo();
				} catch (SQLException error) {

					System.err.println("SQL Error: " + error.getMessage());
				}

				formDet = new FormulariosDetalhe(nome, email, escola,
						storeNameDBContent);
			}
		});
		buttonDetails.setBounds(374, 398, 160, 24);
		frame.getContentPane().add(buttonDetails);
	}

}
